<?php

namespace App\Console\Commands;

use App\Models\DomainList;
use App\Models\Setting as SettingModel;
use App\Notifications\CommonMessage;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Notification;

class DomainCheck extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'domain:check';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $pre_use = json_decode(SettingModel::query()->firstOrCreate(['key' => 'pre_use'], ['value' => null])->value);


        DomainList::query()->where('state', 0)->orderBy('sort')->limit($pre_use)->get()->each(function ($domain) {
            try {
                $result = json_decode(file_get_contents('http://47.242.244.180/bak/check1/index.php?domain=' . $domain->domain));
            }catch (\Exception $exception){
                Log::error('域名检测失败:'.$exception->getMessage());
            }
            if ($result->status == 2) {
                $domain->state = 1;
                $domain->save();
                $count = DomainList::query()->where('state', 0)->count();
                Notification::send(new \stdClass(),
                    new CommonMessage('域名【' . $domain->domain . '】被封，当前系统剩余域名：' . $count . '个')
                );
            }
        });
    }
}
